package com.example.osixaffairssystem.controller;

import com.example.osixaffairssystem.domain.PageBean;
import com.example.osixaffairssystem.domain.Result;
import com.example.osixaffairssystem.domain.model.Std;
import com.example.osixaffairssystem.service.StdService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/std")
@RequiredArgsConstructor
public class StdController {

    final StdService stdService;

    @GetMapping("/list")
    public Result list() {
        log.info("获取学生列表");
        List<Std> list = stdService.list();
        return Result.success(list);
    }

    @GetMapping
    public Result listToPage(@RequestParam() Integer page, @RequestParam() Integer pageSize) {
        log.info("分页查询学生{ page: {}, pageSize: {} }", page, pageSize);
        PageBean<Std> pageBean = stdService.listToPage(page, pageSize);
        return Result.success(pageBean);
    }

    @PostMapping
    public Result insert(@RequestBody Std std) {
        log.info("新增学生{}", std);
        Integer id = null;
        try {
            id = stdService.insert(std);
        } catch (DuplicateKeyException e) {
            return new Result(HttpStatus.CONFLICT.value(), "Duplicate_Key", null);
        }
        return Result.success(id);
    }

    @PutMapping
    public Result update(@RequestBody Std std) {
        log.info("更新学生{}", std);
        stdService.update(std);
        return Result.success();
    }

    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("删除学生{}", ids);
        stdService.delete(ids);
        return Result.success();
    }

    @GetMapping("/search")
    public Result search(@RequestParam(name = "no") String no,
                         @RequestParam(name = "page") Integer page,
                         @RequestParam(name = "pageSize") Integer pageSize) {
        log.info("搜索学生{}", no);
        PageBean<Std> list = stdService.search(no,page,pageSize);
        return Result.success(list);
    }

}
